﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace FileExplorer
{
    public partial class FileExplorerForm : Form
    {
        private readonly BindingList<FileSystemInfo> f_InfoList = new BindingList<FileSystemInfo>();

        private readonly TreeNodeCollection f_RootItemsCollection;

        public FileExplorerForm()
        {
            InitializeComponent();

            f_RootItemsCollection = f_Files_TreeView.Nodes;

            f_InfoList.ListChanged += InfoList_ListChanged;
            f_InfoList.RaiseListChangedEvents = true;
        }

        public void AddFiles(IEnumerable<FileSystemInfo> Info) { Info.Foreach(f_InfoList.Add); }

        private void InfoList_ListChanged(object sender, ListChangedEventArgs e)
        {
            if(e.ListChangedType != ListChangedType.ItemAdded) return;
            var list = (BindingList<FileSystemInfo>)sender;
            var index = e.NewIndex;
            var item = list[index];
            CreateNode(item);
        }

        private void CreateNode(FileSystemInfo Info, TreeNode Parrent = null)
        {
            var node = new TreeNode(Info.Name) { Tag = Info };
            CheckNode(node);
            (Parrent == null ? f_RootItemsCollection : Parrent.Nodes).Add(node);
        }

        private void CheckNode(TreeNode Node)
        {
            var info = (FileSystemInfo)Node.Tag;
            if(info is DirectoryInfo)
            {
                var directory = (DirectoryInfo)info;
                directory.GetDirectories().Foreach(d => CreateNode(d, Node));
                directory.GetFiles().Foreach(f => CreateNode(f, Node));
            }

            info.GetNTFSStreamInfos()
                        .Select(s_info =>
                                new TreeNode(string.Format("{0}:{1}:{2}", info.Name, s_info.Name, s_info.Size)) { Tag = s_info })
                        .Foreach(n => Node.Nodes.Add(n));
        }

        private void f_Files_TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //var view = (TreeView)sender;
            var node = e.Node;
            var tag = node.Tag;

            if(tag is FileInfo)
            {
                var info = (FileInfo)tag;
            }
            else if(tag is DirectoryInfo)
            {
                var info = (DirectoryInfo)tag;
            }
            else if(tag is NTFSDataStreamInfo)
            {
                var info = (NTFSDataStreamInfo)tag;
            }
        }
    }
}
